from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request
from flask import session

from info.models import User, News, Category
from info.utils.captcha.response_code import RET
from info.utils.common import user_login_data
from . import index_blu


@index_blu.route('/news_list')
def news_list():
    cid = request.args.get('cid', '1')
    page = request.args.get('page', '1')
    per_page = request.args.get('per_page', '10')

    try:
        page = int(page)
        per_page = int(per_page)
        cid = int(cid)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    filters = []
    if cid != 1:
        filters.append(News.category_id == cid)
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    news_model_list = paginate.items
    total_page = paginate.pages
    current_page = paginate.page

    news_dict_list = []
    for news in news_model_list:
        news_dict_list.append(news.to_basic_dict())

    data = {
        'total_page': total_page,
        'news_dict_list': news_dict_list,
        'current_page': current_page
    }

    return jsonify(errno=RET.OK, errmsg='ok', data=data)


@index_blu.route('/')
@user_login_data
def index():
    # 获取到当前登录用户的id
    # user_id = session.get("user_id")
    # # 通过id获取用户信息
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)
    user = g.user

    # 获取右侧排行
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(6)
    except Exception as e:
        current_app.logger.error(e)

    click_news_list = []
    for news in news_list if news_list else []:
        click_news_list.append(news.to_basic_dict())

    # 新闻分类展示
    categories = Category.query.all()

    category_li = []
    for category in categories:
        category_li.append(category.to_dict())

    data = {
        'user_info': user.to_dict() if user else None,
        'click_news_list': click_news_list,
        'category_li': category_li
    }

    return render_template('news/index.html', data=data)


@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')